/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package maincz.tests.webapp.dao;

import java.util.List;
import java.util.logging.Logger;

import maincz.tests.webapp.entity.Cache;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author Main
 */
@Repository
@Transactional
public class CachesDAO implements ICachesDAO {

    @Autowired
    private SessionFactory sessionFactory;

    private static final Logger log = Logger.getLogger("MyLogger");

    public CachesDAO() {
        super();
        log.info("constructor CachesDAOImpl");
    }

    @Override
    public void addCache(Cache cache) {
        sessionFactory.getCurrentSession().save(cache);
    }

    @Override
    public void updateCache(Cache cache) {
        sessionFactory.getCurrentSession().update(cache);
    }

    @Override
    public void addOrUpdate(Cache cache) {
        sessionFactory.getCurrentSession().saveOrUpdate(cache);
    }
        
    @Override
    public List<Cache> listCaches() {
        return sessionFactory.getCurrentSession().createQuery("from Cache").list();
    }

    @Override
    public Cache getCacheByCode(String geocode) {
        return  (Cache) sessionFactory.getCurrentSession()
                .createQuery("from Cache as cache where cache.geocode = ?")
                .setString(0, geocode).list().get(0);
    }

    @Override
    public void removeCache(String geocode) {
        List<Cache> toRemove = sessionFactory.getCurrentSession()
                .createQuery("from Cache as cache where cache.geocode = ?")
                .setString(0, geocode).list();
        for (Cache cache: toRemove) {
            sessionFactory.getCurrentSession().delete(cache);
        }
        
    }
    
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

}
